package net.alan.modules.service.impl;

import net.alan.common.utils.Base64;
import net.alan.modules.bean.Result;
import net.alan.modules.bean.ResultUtil;
import net.alan.modules.bean.User;
import net.alan.modules.mail.EmailConfig;
import net.alan.modules.service.IEmailService;
import net.alan.modules.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/12/15
 */
@Service
public class EmailServiceImpl implements IEmailService {
    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private IUserService userService;

    @Override
    public Result sendSimpleMail(String sendTo, String url, String sessionId) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            User user = userService.getUserByEmail(sendTo);
            if (user == null)
                return ResultUtil.error("该邮箱不存在");
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailConfig.getEmailFrom());
            helper.setTo(sendTo);
            helper.setSubject("【云协作平台】找回密码");
            url = url + "/home/my/findpass?code=" + Base64.encodeString(user.getEmail()) + "&sessionId=" + sessionId;
            StringBuffer sb = new StringBuffer();
            sb.append("<html><body>");
            sb.append("<div>你好:" + user.getName() + "</div>");
            sb.append("<div>通过点击下面的链接重置您的密码<a href=" + url + ">" + url + "</a></div>");
            sb.append("</body></html>");
            helper.setText(sb.toString(), true);
            mailSender.send(mimeMessage);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultUtil.error("网络错误，发送失败");
    }

}
